#!/usr/bin/env python3
# -*- coding:utf-8 -*-
####################################################################################################
# File: cmd.py                                                                                     #
# Created Date: Friday, December 16th 2022, 10:08:52 pm                                            #
# Author: Zongliang Hou                                                                            #
# E-mail: EnderZ@sjtu.edu.cn                                                                       #
# Copyright (c) 2022 Lei Lab                                                                       #
####################################################################################################
import argparse
import sys
sys.path.append("/Users/ender/Code_repo/rosalind-brush-questions")
from utils import read_fasta


def get_kmers(sequence: str, kmer_length: int = 2):
    if kmer_length < 2:
        raise ValueError("K-mer's length must be more than 2")
    if kmer_length > len(sequence):
        raise ValueError("K-mer's length must be less than the length of sequence")

    i = 0
    kmers = []
    while i + kmer_length <= len(sequence):
        kmers.append(sequence[i:i+kmer_length])
        i += 1
    # kmers = set([sequence[i:i+kmer_length] for i in range(len(sequence) - kmer_length)])
    return set(kmers)


parser = argparse.ArgumentParser()
parser.add_argument("--fasta", "-f")
args = parser.parse_args()

fasta = read_fasta(args.fasta)

min_sub_str_len = 2
max_sub_str_len = min([len(seq) for seq in fasta.values()])

sub_str_len = min_sub_str_len
while sub_str_len <= max_sub_str_len:
    sub_strs_dict = {}
    for name, sequence in fasta.items():
        sub_strs_dict[name] = get_kmers(sequence, sub_str_len)

    tmp_common_sub_strs = sub_strs_dict.pop(name)
    for name, sub_strs in sub_strs_dict.items():
        tmp_common_sub_strs = tmp_common_sub_strs.intersection(sub_strs)

    sub_str_len += 1
    if len(tmp_common_sub_strs) > 0:
        common_sub_strs = tmp_common_sub_strs

print(common_sub_strs)
